public class Solution42 {
    public int trap(int[] height) {
        int res = 0, temp = 0;
        int left = 0, right = 0;
        for (int h : height) {
            if (h >= left) {
                left = h;
                res += temp;
                temp = 0;
            } else {
                temp += left - h;
            }
        }
        temp = 0;
        for (int i = height.length - 1; i >= 0; i--) {
            int h = height[i];
            if (h > right) {
                right = h;
                res += temp;
                temp = 0;
            } else {
                temp += right - h;
            }
        }

        return res;
    }
}
